class GioHang
  include MongoMapper::Document

  before_save :mac_dinh

  key :dia_chi_nhan_hang,     String
  key :dien_thoai_lien_lac,   String
  key :da_xu_ly,              Boolean
  key :da_xac_nhan,           Boolean
  key :thoi_gian_dat_hang,    Time
  belongs_to :nhan_vien_giao_hang, :class_name => "NguoiDung"
  belongs_to :nhan_vien_xu_ly, :class_name => "NguoiDung"
  belongs_to :nguoi_dung
  many :san_pham_muas
  timestamps!
  def mac_dinh
    if self.da_xu_ly.nil?
    self.da_xu_ly = false
    end
    if self.da_xac_nhan.nil?
      self.da_xac_nhan = false
    end
  end

  def them_san_pham(san_pham_id)
    sp_mua = SanPhamMua.where(:san_pham_id => san_pham_id, :gio_hang_id => self.id).first;
    if sp_mua
      sp_mua.so_luong = sp_mua.so_luong + 1
      sp_mua.save
    else
      san_pham = SanPham.find(san_pham_id)
      if san_pham.present?
        sp_mua = SanPhamMua.create({
          :san_pham => san_pham,
          :so_luong => 1,
          :gio_hang => self,
          :gia_mua => san_pham.co_khuyen_mai(Time.now) ? san_pham.gia_khuyen_mai : san_pham.gia
        })
      self.san_pham_muas << sp_mua
      self.save
      else
      return false;
      end
    end
    return true
  end

  def tong_gia_tri
    gia_tri = 0;
    for t in self.san_pham_muas
      gia_tri += t.so_luong * t.gia_mua
    end
    return gia_tri
  end

end

class SanPhamMua
  include MongoMapper::Document

  key :so_luong,  Integer
  key :gia_mua,   Integer
  belongs_to :san_pham
  belongs_to :gio_hang
end